# -*- coding: binary -*-

# Module to get version of splunk app
module Msf::Exploit::Remote::HTTP::Splunk::Version
  # Extracts the Splunk version information using authenticated cookie if available
  #
  # @param cookie_string [String] Valid cookie if available
  # @return [String, nil] Splunk version if found, nil otherwise
  def splunk_version(cookie_string = nil)
    version = splunk_version_authenticated(cookie_string) if !cookie_string.nil?
    return version if version

    version = splunk_login_version
    return version if version

    nil
  end

  private

  # Extracts splunk version from splunk user page using valid cookie
  #
  # @param cookie_string [String] Valid cookie
  # @return [String] Splunk version
  def splunk_version_authenticated(cookie_string)
    res = send_request_cgi({
      'uri' => splunk_user_page,
      'vars_get' => {
        'output_mode' => 'json'
      },
      'headers' => {
        'Cookie' => cookie_string
      }
    })

    return nil unless res&.code == 200

    body = res.get_json_document
    body.dig('generator', 'version')
  end

  # Tries to extract splunk verion from login page
  #
  # @return [String, nil] Splunk version if found, otherwise nil
  def splunk_login_version
    res = send_request_cgi({
      'uri' => splunk_url_login,
      'method' => 'GET'
    })

    if res
      match = res.body.match(/Splunk \d+\.\d+\.\d+/)
      return match[0].split[1] if match
    end
  end
end
